package com.hzb.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hzb.common.to.es.SkuEsModel;
import com.hzb.gulimall.search.canstent.EsCanstent;
import com.hzb.gulimall.search.config.GlimallSearchConfig;
import com.hzb.gulimall.search.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //数据保存到es中
        //给es中建立一个索引，product，建立映射关系

        //给es中包旭年数据
        BulkRequest bulkRequest = new BulkRequest();
        //构建批量操作
        for (SkuEsModel skuEsModel : skuEsModels) {
            //构建保存的请求
            IndexRequest indexRequest = new IndexRequest(EsCanstent.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());//当前商品的sku的id
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GlimallSearchConfig.COMMON_OPTIONS);
        //TODO 1.如果批量错误，就可以处理错误
        boolean b = bulk.hasFailures();
        if (b){
            String s = bulk.buildFailureMessage();
            log.error("商品上架失败：{}",s);
        }
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{}",collect,bulk.toString());
        return b;
    }
}
